package com.yuedong.down;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;


import com.yuedong.down.progress.DownLoadProgressbar;
import com.yuedong.down.util.DialogUtil;

import java.util.List;

public class DownLoadManager {
    private static DownLoadManager downLoadManager;
    private DialogUtil dialogUtil;
    private DownLoadProgressbar dProgress;
    private Activity activity;
    private Dialog commentDialog;
    private DownLoadCallBack callBack;
    private String url;
    private static int logo;

    public DownLoadManager() {
        dialogUtil = new DialogUtil();
    }

    public static DownLoadManager getInstance() {
        if (null == downLoadManager) {
            downLoadManager = new DownLoadManager();
        }
        return downLoadManager;
    }

    public static DownLoadManager getInstance(int notifyLogo) {
        if (null == downLoadManager) {
            logo = notifyLogo;
            downLoadManager = new DownLoadManager();
        }
        return downLoadManager;
    }

    private DownloadService.DownloadBinder downloadBinder;
    private DownloadService downloadService;
    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadBinder = (DownloadService.DownloadBinder) service;
            downloadService = downloadBinder.getDownLoadService();
            downloadService.setProgressCallBack(new DownloadService.ProgressCallBack() {
                @Override
                public void onProgress(int pro) {
                    Message message = new Message();
                    message.obj = pro;
                    mHandler.sendMessage(message);
                }
            });

        }

        Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.obj instanceof Integer) {
                    final int pro = (int) msg.obj;
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (dProgress != null) dProgress.setCurrentValue(pro);
                            if (callBack != null) callBack.progress(pro);
                        }
                    });
                    if (pro == 100) {
                        if (commentDialog != null) {
                            commentDialog.dismiss();
                            commentDialog = null;
                        }
                    }
                }

            }
        };

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    public void defaultDownLoad(Activity activity, final String content, final int forceUpdate, final String url) {
        this.url = url;
        bindService(activity);
        if (verifyStoragePermissions(activity))
            update(content, forceUpdate, url);
    }

    public void downLoadApk(Activity activity, final String url, Dialog commentDialog, DownLoadCallBack callBack) {
        this.commentDialog = commentDialog;
        this.callBack = callBack;
        this.url = url;
        setNotifyLogo(logo);
        if (verifyStoragePermissions(activity))
            downloadBinder.startDownload(url);

    }

    public void downLoadApk(Activity activity, final String url, Dialog commentDialog) {
        this.commentDialog = commentDialog;
        this.url = url;
        setNotifyLogo(logo);
        // bindService(activity);
        if (verifyStoragePermissions(activity))
            downloadBinder.startDownload(url);


    }

    public void cancleDownLoad() {
        if (downloadBinder != null) downloadBinder.cancelDownload();
    }

    public void paseDownLoad() {
        if (downloadBinder != null) downloadBinder.pauseDownload();
    }

    /**
     * 继续下载
     */
    public void downLoadTry() {
        if (downloadBinder != null) downloadBinder.startDownload(url);
    }

    /**
     * 重新下载
     */
    public void downLoadAgain() {
        if (downloadBinder != null) {
            downloadBinder.cancelDownload();
            downloadBinder.startDownload(url);
        }
    }

    public void bindService(Activity activity) {
        this.activity = activity;
        Intent intent = new Intent(activity, DownloadService.class);
        activity.startService(intent);  //启动服务
        activity.bindService(intent, connection, activity.BIND_AUTO_CREATE);//绑定服务
        setNotifyLogo(logo);
    }

    public void unBindService(Activity activity) {
      if(null!=downloadService)  activity.unbindService(connection);

    }

    /**
     * @param content     更新内容
     * @param forceUpdate 是否强制更新
     * @param url         更新下载地址
     */
    private void update(String content, final int forceUpdate, final String url) {
        commentDialog = null;
        commentDialog = dialogUtil.showCommentDilog(activity, R.layout.dialog_newupdate);
        dProgress = (DownLoadProgressbar) commentDialog.findViewById(R.id.dProgress);
        final TextView tvContent = (TextView) commentDialog.findViewById(R.id.tvContent);
        final TextView tvQuit = (TextView) commentDialog.findViewById(R.id.tvQuit);
        final TextView tvUpdate = (TextView) commentDialog.findViewById(R.id.tvUpdate);
        dProgress.setMaxValue(100);
        tvContent.setText(TextUtils.isEmpty(content) ? "" : content.replace("#", ""));

        tvQuit.setText(activity.getString(R.string.cancel));
        if (forceUpdate == 1) {
            tvQuit.setText(activity.getString(R.string.quite));
        }
        tvQuit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (tvQuit.getText().toString().equals(activity.getString(R.string.quite))) {
                    activity.finish();
                } else if (tvQuit.getText().toString().equals(activity.getString(R.string.cancel_down))) {
                    downloadBinder.cancelDownload();
                    commentDialog.dismiss();
                    commentDialog = null;
                } else if (tvQuit.getText().toString().equals(activity.getString(R.string.cancel))) {
                    commentDialog.dismiss();
                    commentDialog = null;
                }
            }
        });
        tvUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (tvUpdate.getText().toString().equals(activity.getString(R.string.update))) {
                    tvUpdate.setText(activity.getString(R.string.hide));
                    if (forceUpdate != 1)
                        tvQuit.setText(activity.getString(R.string.cancel_down));
                    tvContent.setVisibility(View.GONE);
                    dProgress.setVisibility(View.VISIBLE);
                    if (downloadBinder != null) {
                        setNotifyLogo(logo);
                        downloadBinder.startDownload(url);
                    }
                } else if (tvUpdate.getText().toString().equals(activity.getString(R.string.hide))) {
                    commentDialog.dismiss();
                    commentDialog = null;
                }
            }
        });
    }

    public interface DownLoadCallBack {
        void progress(int p);
    }

    public interface onClickResultListener {
        void onCancel();

    }

    public void setNotifyLogo(int logoRes) {
        if (null != downloadService) downloadService.setNotifyLogo(logoRes);
    }

    public static boolean verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
            return false;
        }
        return true;
    }

}
